﻿namespace USElections.Newsfeed.Pages
{
    using System;
    using System.Diagnostics;
    using System.ServiceModel.Syndication;
    using System.Windows.Data;
    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Shell;
    using Microsoft.Phone.Tasks;
    using NorthernLights;
    using USElections.Utils;

    /// <summary>
    /// FeedReaderPage class.
    /// </summary>
    public partial class FeedReaderPage : PhoneApplicationPage
    {
        #region Fields
        private PagedCollectionView pcv;
        #endregion

        #region Constructor
        /// <summary>
        /// Initializes a new instance of the FeedReaderPage class.
        /// </summary>
        public FeedReaderPage()
        {
            InitializeComponent();

            this.webbrowser.LoadCompleted += (sender, e) =>
            {
                SystemTray.ProgressIndicator.IsVisible = false;
            };
        }
        #endregion

        #region Public methods
        /// <summary>
        /// OnNavigatedTo event.
        /// </summary>
        /// <param name="e">The NavigationEventArgs.</param>
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            int feed = StateVariables.Get<int>("Feed");
            int feeditem = StateVariables.Get<int>("FeedItem");

            try
            {
                this.pcv = NewsFeeds.Model.Data.Instance.RssFeeds[feed].Items;
                this.pcv.MoveCurrentToPosition(feeditem);

                this.SetPositionText();
                SystemTray.ProgressIndicator.IsVisible = true;
                this.DataContext = this.pcv.CurrentItem as SyndicationItem;
            }
            catch
            {
                if (NavigationService.CanGoBack)
                {
                    // error occurred.
                    NavigationService.GoBack();
                }
                else
                {
                    this.NavigationService.Navigate(new Uri("/USElections;component/Pages/MainPage.xaml", UriKind.Relative));
                }
            }
        }

        /// <summary>
        /// The OnNavigatedFrom event.
        /// </summary>
        /// <param name="e">The NavigationEventArgs.</param>
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
        }
        #endregion

        #region Private methods
        private void SetPositionText()
        {
            int currentPos = this.pcv.CurrentPosition;
            int totalItems = this.pcv.Count;

            this.posTxt.Text = string.Format("{0} / {1}", currentPos + 1, totalItems);
        }

        private void ApplicationBarIconButtonClick(object sender, EventArgs e)
        {
            ApplicationBarIconButton item = sender as ApplicationBarIconButton;

            if (item != null)
            {
                string s = item.Text.ToLowerInvariant();

                switch (s)
                {
                    case "previous":
                        if (this.pcv.MoveCurrentToPrevious())
                        {
                            int feeditem = StateVariables.Get<int>("FeedItem");
                            StateVariables.Set<int>("FeedItem", feeditem - 1);

                            this.SetPositionText();
                            SystemTray.ProgressIndicator.IsVisible = true;
                            this.DataContext = this.pcv.CurrentItem as SyndicationItem;
                        }

                        break;
                    case "next":
                        if (this.pcv.MoveCurrentToNext())
                        {
                            int feeditem = StateVariables.Get<int>("FeedItem");
                            StateVariables.Set<int>("FeedItem", feeditem + 1);

                            this.SetPositionText();
                            SystemTray.ProgressIndicator.IsVisible = true;
                            this.DataContext = this.pcv.CurrentItem as SyndicationItem;
                        }

                        break;
                    case "share":
                        SyndicationItem currentItem = this.pcv.CurrentItem as SyndicationItem;

                        if (currentItem != null)
                        {
                            string url = currentItem.Id;

                            BitLyUrlShortener.Execute(url, (shortenedUrl) =>
                                {
                                    ShareStatusTask sst = new ShareStatusTask();
                                    string title = currentItem.Title.Text;

                                    if (title.Length > 40)
                                    {
                                        title = title.Substring(0, 37) + "...";
                                    }

                                    string status = string.Format("Check this interesting article: {0} at {1} (using @uselectionsapp #wp)", title, shortenedUrl);

                                    sst.Status = status;

                                    if (sst.Status.Length > 140)
                                    {
                                        Debug.WriteLine("WARNING: Status too long for twitter!");
                                    }

                                    try
                                    {
                                        sst.Show();
                                    }
                                    catch
                                    {
                                    }
                                });

                        }
                        break;
                }
            }
        }
        #endregion
    }
}